using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace UnityGameFramework.Runtime
{
    /// <summary>
    /// 注意如果存在多个继承的子类，其子类会覆盖父类的Instance，所以建议每个继承的子类使用sealed限制更下一层的继承。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class PreloadRuntimeSettingScriptableObject<T> : ScriptableObject
        where T: PreloadRuntimeSettingScriptableObject<T>
    {
        public static T Instance { get; private set; }

#if UNITY_EDITOR
        private static readonly Type s_SelfType = typeof(T);
        public static T SettingObject
        {
            get
            {
                if (EditorBuildSettings.TryGetConfigObject(s_SelfType.FullName, out T setting))
                {
                    foreach (var item in AssetDatabase.FindAssets($"t:{nameof(T)}"))
                    {
                        string path = AssetDatabase.GUIDToAssetPath(item);
                        setting = AssetDatabase.LoadAssetAtPath<T>(path);
                        SettingObject = setting;
                        break;
                    }
                }
                return setting;
            }
            set
            {
                EditorBuildSettings.AddConfigObject(s_SelfType.FullName, value, true);
                Instance = value;
            }
        }

        /// <summary>
        /// 子类须调用初始化操作，添加[InitializeOnLoadMethod]
        /// </summary>

        protected static void CheckInstance()
        {
            var setting = SettingObject;
            if (setting)
            {
                Instance = setting;
            }
        }

        private void OnEnable()
        {
            if (Instance && Instance != null)
            {
                Debug.LogError($"Multiple {nameof(T)} asset NOT allowed!");
            }
            var setting = SettingObject;
            if (SettingObject)
            {
                Instance = setting;
            }
        }
#else
        private void Awake()
        {
            Debug.Log($"{typeof(T).FullName} awakening...");
            if (Instance && Instance != this)
            {
                Debug.LogError($"Multiple {nameof(T)} instance NOT allowed!");
            }
            if (!Instance)
            {
                Instance = (T)this;
                DontDestroyOnLoad(Instance);
            }
        }
#endif
    }
}
